/**
 * 实现按钮
 * 创建者：Carburn Ashroom
 * 2023.11.16
 */

class Button {      // Button类提供了一个可以改变大小的按钮

    constructor(x, y, text, cls =btnClr, size =btnSize, smallRatio =btnRatio, textClr =btnFontC, font =btnFont, fontsz =btnTextSz) {
        this.pos = [x, y];
        this.size = size;
        this.text = text;
        this.color = cls;
        this.xRatio = size[0] * smallRatio;
        this.yRatio = size[1] * smallRatio;
        this.strength = false;
        this.textClr = textClr;
        this.clicked = false;
        this.font = font;
        this.textSz = fontsz;
        this.fontRatio = fontsz * smallRatio;
    }

    contains(pos) { return this.pos[0] < pos[0] && this.pos[1] < pos[1] && pos[0] < this.pos[0]+this.size[0] && pos[1] < this.pos[1]+this.size[1]; }

    isClicked() { return (this.clicked) ? !(this.clicked = false) : false; }

    onMouseDown(pos) { this.strength = this.contains(pos); }

    onMouseUp(pos) {        // 松开鼠标
        if (this.strength) {
            this.clicked = this.contains(pos);
        }
        this.strength = false;
    }

    moveTo(pos) { this.pos = pos; }

    draw(context) {     // 绘制
        let rtX = (this.strength) ? this.xRatio : 0;
        let rtY = (this.strength) ? this.yRatio : 0;
        context.fillStyle = this.color;
        context.fillRect(this.pos[0]+rtX, this.pos[1]+rtY, this.size[0]-2*rtX, this.size[1]-2*rtY);
        context.textBaseline = "middle";
        context.textAlign = "center";
        let rtFont = (this.strength) ? this.fontRatio : 0;
        context.font = this.textSz - rtFont + "px " + this.font;
        context.fillStyle = this.textClr;
        context.fillText(this.text, this.pos[0]+this.size[0]/2, this.pos[1]+this.size[1]/2);
    }

    clear() {       // 初始化状态
        this.strength = false;
        this.clicked = false;
    }

}
